package com.disgruntledbots;

import org.andengine.engine.camera.ZoomCamera;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.PinchZoomDetector;
import org.andengine.input.touch.detector.PinchZoomDetector.IPinchZoomDetectorListener;


public class CameraController implements IOnSceneTouchListener,
		IPinchZoomDetectorListener {
	private static final float MIN_ZOOM_FACTOR = 0.5f;
	private static final float MAX_ZOOM_FACTOR = 1.5f;
	
	private PinchZoomDetector mPinchZoomDetector;
	
	private float mInitialTouchZoomFactor;
	
	ZoomCamera mCamera;
	
	public CameraController(ZoomCamera camera)
	{
		mPinchZoomDetector = new PinchZoomDetector(this);
		
		// Enable the zoom detector
		mPinchZoomDetector.setEnabled(true);

		this.mCamera = camera;
	}
	
	@Override
	public void onPinchZoomStarted(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pSceneTouchEvent) {
		mInitialTouchZoomFactor = mCamera.getZoomFactor();

	}

	@Override
	public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pTouchEvent, float pZoomFactor) {

		final float newZoomFactor = mInitialTouchZoomFactor * pZoomFactor;
		
		// If the camera is within zooming bounds
		if(newZoomFactor < MAX_ZOOM_FACTOR && newZoomFactor > MIN_ZOOM_FACTOR){
			// Set the new zoom factor
			mCamera.setZoomFactor(newZoomFactor);
		}

	}

	@Override
	public void onPinchZoomFinished(PinchZoomDetector pPinchZoomDetector,
			TouchEvent pTouchEvent, float pZoomFactor) {
		// Set the zoom factor one last time upon ending the pinch-to-zoom functionality
		final float newZoomFactor = mInitialTouchZoomFactor * pZoomFactor;

		// If the camera is within zooming bounds
		if(newZoomFactor < MAX_ZOOM_FACTOR && newZoomFactor > MIN_ZOOM_FACTOR){
			// Set the new zoom factor
			mCamera.setZoomFactor(newZoomFactor);
		}
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		// TODO Auto-generated method stub
		this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);
		return true;
	}

}
